package com.core.shared;


import com.core.model.UploadImage;
import org.apache.commons.codec.binary.Base64;
import org.imgscalr.AsyncScalr;
import org.imgscalr.Scalr;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-10-8
 * Time: 上午10:09
 * To change this template use File | Settings | File Templates.
 */
public class ImageUtils {

    public static final String PNG = "png";
    public static final String JPG = "jpg";


    public static java.util.List<UploadImage> resolveUploadImages(java.util.List<MultipartFile> list) {
        List<UploadImage> documents = new ArrayList<>();
        for (MultipartFile file : list) {
            UploadImage document = multipartFileToUploadImage(file);
            documents.add(document);
        }
        return documents;
    }

    public static void showImageByContents(byte[] contents, HttpServletResponse response) {
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(contents);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static UploadImage multipartFileToUploadImage(MultipartFile m) {
        UploadImage document = null;
        try {
            String imageName = m.getOriginalFilename();
            String contentType = m.getContentType();
            byte[] bytes = m.getBytes();
            document = new UploadImage(imageName, contentType, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }

    public static byte[] base64Decoder(String str) {
        return Base64.decodeBase64(str);
    }

    public static String base64Encoder(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 上传
     *
     * @param file
     */
    public static void upload(String filePath, MultipartFile file) {
        if (file != null) {
            String fileName = file.getOriginalFilename();
            File target = new File(filePath);
            if (!target.exists()) {
                target.mkdirs();
            }
            File targetFile = new File(filePath + "\\" + fileName);
            try {
                BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
                byte[] b = new byte[1024];
                int i = bis.read(b);
                while (i != -1) {
                    bos.write(b, 0, i);
                    i = bis.read(b);
                }
                bis.close();
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载
     *
     * @param response
     */
    public static void download(HttpServletResponse response) {
        File file = new File("e:/upload/1.png");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] b = new byte[1024];
            int i;
            while ((i = bis.read(b)) > 0) {
                bos.write(b, 0, i);
            }
            bis.close();
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void resize(int w, int h, BufferedImage sourceImg, OutputStream outputStream) {
        Future<BufferedImage> future = AsyncScalr.resize(sourceImg, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, w, h);
        try {
            BufferedImage outImage = future.get();
            ImageIO.write(outImage, PNG, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        File file = new File("D:\\xxx123.jpg");   //处理后上传到ftp
//        ImageIO.write(image, "jpg", file);
//        FTPHandle.uploadFile("192.168.0.103", 21, "lxf", "123456", "/", "xxx123.jpg", new FileInputStream(file));
    }


    public static Map<String, Object> uploadImageHandle(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        if ("image/jpeg".equals(file.getContentType()) || "image/png".equals(file.getContentType()) || "image/gif".equals(file.getContentType())) {
            if (file.getSize() >= (1024 * 1024 * 2)) {      // 限制2M
                map.put("result", "file_too_large");
            }
        } else {
            map.put("result", "file_type_not_allowed");
        }
        return map;
    }

    /**
     * 更改图片格式
     *
     * @param source    源图片
     * @param target    新图片
     * @param imageType 期望的图片格式
     */
    public static void changeImageType(File source, File target, String imageType) {
        try {
            BufferedImage bufferedImage = ImageIO.read(source);
            ImageIO.write(bufferedImage, imageType, target);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
